package com.joe.learn.acm;

import java.util.Arrays;

public class MegrSort {


    public static void main(String[] args) {
        int data[] = {9, 5, 6, 8, 0, 3, 7, 1};

        megerSort(data, 0, data.length - 1);
        System.out.println(Arrays.toString(data));

    }

    public static void megerSort(int data[], int left, int right) {

        if (left < right) {
            int mid = (left + right) / 2;
            megerSort(data, left, mid);
            megerSort(data, mid + 1, right);
            //分完了，就要进行合并
            meger(data, left, mid, right);
        }

    }

    public static void meger(int data[], int left, int mid, int right) {
        int temp[] = new int[data.length];
        int point1 = left;//表示左边的第一个数的位置

        int point2 = mid + 1;//表示右边第一个数字

        int loc = left;

        while (point1 <= mid && point2 <= right) {
            if (data[point1] < data[point2]) {
                temp[loc] = data[point1];
                point1++;
                loc++;
            } else {
                temp[loc] = data[point2];
                point2++;
                loc++;
            }
        }

        while (point1 <= mid) {
            temp[loc++] = data[point1++];
        }

        while (point2 <= right) {
            temp[loc++] = data[point2++];
        }

        for (int i = left; i <= right; i++) {
            data[i] = temp[i];
        }
    }

}
